Page({
  data: {
    statusBarHeight: 0,
    carPrice: 200000, // 车辆价格（元）
    downPaymentRate: 30, // 首付比例（%）
    downPayment: 60000, // 首付金额（元）
    loanAmount: 140000, // 贷款金额（元）
    loanTerm: 36, // 贷款期限（月）
    interestRate: 4.35, // 年利率（%）
    repaymentMethod: 'equal_installment', // 还款方式：等额本息(equal_installment)或等额本金(equal_principal)
    
    // 计算结果
    monthlyPayment: 0, // 月供（元）
    totalInterest: 0, // 总利息（元）
    totalPayment: 0, // 还款总额（元）
    
    // 分期详情
    installmentDetails: [],
    
    // 期限选项
    terms: [
      { label: '12期(1年)', value: 12 },
      { label: '24期(2年)', value: 24 },
      { label: '36期(3年)', value: 36 },
      { label: '48期(4年)', value: 48 },
      { label: '60期(5年)', value: 60 }
    ],
    
    // 首付比例选项
    downPaymentRates: [
      { label: '30%', value: 30 },
      { label: '40%', value: 40 },
      { label: '50%', value: 50 },
      { label: '60%', value: 60 }
    ],
    
    showResultDetail: false
  },

  onLoad: function () {
    // 获取状态栏高度
    const systemInfo = wx.getSystemInfoSync();
    this.setData({
      statusBarHeight: systemInfo.statusBarHeight
    });
    
    // 初始化计算
    this.calculateLoan();
  },
  
  // 返回上一页
  handleBack: function () {
    wx.navigateBack();
  },
  
  // 车价输入变化
  onCarPriceChange: function (e) {
    const carPrice = parseFloat(e.detail.value || 0);
    const downPaymentRate = this.data.downPaymentRate;
    const downPayment = Math.round(carPrice * downPaymentRate / 100);
    const loanAmount = carPrice - downPayment;
    
    this.setData({
      carPrice,
      downPayment,
      loanAmount
    });
    
    this.calculateLoan();
  },
  
  // 首付比例变化
  onDownPaymentRateChange: function (e) {
    const downPaymentRate = parseFloat(e.detail.value);
    const carPrice = this.data.carPrice;
    const downPayment = Math.round(carPrice * downPaymentRate / 100);
    const loanAmount = carPrice - downPayment;
    
    this.setData({
      downPaymentRate,
      downPayment,
      loanAmount
    });
    
    this.calculateLoan();
  },
  
  // 贷款期限变化
  onLoanTermChange: function (e) {
    const loanTerm = parseInt(e.detail.value);
    
    this.setData({
      loanTerm
    });
    
    this.calculateLoan();
  },
  
  // 利率变化
  onInterestRateChange: function (e) {
    const interestRate = parseFloat(e.detail.value || 0);
    
    this.setData({
      interestRate
    });
    
    this.calculateLoan();
  },
  
  // 还款方式变化
  onRepaymentMethodChange: function (e) {
    const repaymentMethod = e.detail.value;
    
    this.setData({
      repaymentMethod
    });
    
    this.calculateLoan();
  },
  
  // 计算贷款
  calculateLoan: function () {
    const { loanAmount, loanTerm, interestRate, repaymentMethod } = this.data;
    
    // 月利率
    const monthlyRate = interestRate / 100 / 12;
    
    let monthlyPayment = 0;
    let totalInterest = 0;
    let installmentDetails = [];
    
    if (repaymentMethod === 'equal_installment') {
      // 等额本息
      monthlyPayment = this.calculateEqualInstallment(loanAmount, monthlyRate, loanTerm);
      totalInterest = monthlyPayment * loanTerm - loanAmount;
      
      // 生成分期详情
      installmentDetails = this.generateEqualInstallmentDetails(loanAmount, monthlyRate, loanTerm);
    } else {
      // 等额本金
      const principalPayment = loanAmount / loanTerm;
      
      // 首月还款金额
      monthlyPayment = principalPayment + loanAmount * monthlyRate;
      
      // 计算总利息
      totalInterest = ((loanAmount * monthlyRate * (loanTerm + 1)) / 2);
      
      // 生成分期详情
      installmentDetails = this.generateEqualPrincipalDetails(loanAmount, monthlyRate, loanTerm);
    }
    
    this.setData({
      monthlyPayment: monthlyPayment.toFixed(2),
      totalInterest: totalInterest.toFixed(2),
      totalPayment: (parseFloat(loanAmount) + parseFloat(totalInterest)).toFixed(2),
      installmentDetails
    });
  },
  
  // 计算等额本息月供
  calculateEqualInstallment: function (principal, monthlyRate, term) {
    if (monthlyRate === 0) {
      return principal / term;
    }
    
    return principal * monthlyRate * Math.pow(1 + monthlyRate, term) / (Math.pow(1 + monthlyRate, term) - 1);
  },
  
  // 生成等额本息详情
  generateEqualInstallmentDetails: function (principal, monthlyRate, term) {
    const monthlyPayment = this.calculateEqualInstallment(principal, monthlyRate, term);
    const details = [];
    let remainingPrincipal = principal;
    
    for (let i = 1; i <= term; i++) {
      const interest = remainingPrincipal * monthlyRate;
      const principalPayment = monthlyPayment - interest;
      remainingPrincipal -= principalPayment;
      
      details.push({
        term: i,
        payment: monthlyPayment.toFixed(2),
        principal: principalPayment.toFixed(2),
        interest: interest.toFixed(2),
        remainingPrincipal: Math.max(0, remainingPrincipal).toFixed(2)
      });
    }
    
    return details;
  },
  
  // 生成等额本金详情
  generateEqualPrincipalDetails: function (principal, monthlyRate, term) {
    const principalPayment = principal / term;
    const details = [];
    let remainingPrincipal = principal;
    
    for (let i = 1; i <= term; i++) {
      const interest = remainingPrincipal * monthlyRate;
      const payment = principalPayment + interest;
      remainingPrincipal -= principalPayment;
      
      details.push({
        term: i,
        payment: payment.toFixed(2),
        principal: principalPayment.toFixed(2),
        interest: interest.toFixed(2),
        remainingPrincipal: Math.max(0, remainingPrincipal).toFixed(2)
      });
    }
    
    return details;
  },
  
  // 显示/隐藏还款详情
  toggleResultDetail: function () {
    this.setData({
      showResultDetail: !this.data.showResultDetail
    });
  }
}) 